/**
 * 创建菜单
 * @returns {Function}
 */
const rpn = require('request-promise-native');
const {wechat} = require('./accessToken');

const menuData = {
    "button": [
        {
            "type": "click",
            "name": "今日歌曲",
            "key": "V1001_TODAY_MUSIC",
            "sub_button": []
        },
        {
            "type": "click",
            "name": "歌手简介",
            "key": "V1001_TODAY_SINGER",
            "sub_button": []
        },
        {
            "name": "菜单",
            "sub_button": [
                {
                    "type": "view",
                    "name": "搜索",
                    "url": "http://www.soso.com/",
                    "sub_button": []
                },
                {
                    "type": "view",
                    "name": "视频",
                    "url": "http://v.qq.com/",
                    "sub_button": []
                },
                {
                    "type": "click",
                    "name": "赞一下我们",
                    "key": "V1001_GOOD",
                    "sub_button": []
                }
            ]
        }
    ]
}

// 创建菜单
function createMenu(menu) {
    return new Promise(async (resolve, reject) => {
        try {
            // 获取access_token
            const data = await wechat.fetchAccessToken();
            // 定义请求地址
            const url = `https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${data.access_token}`;
            // 发送请求
            const result = await rpn({method: 'POST', url, json: true, body: menu});
            resolve(result);
        } catch (e) {
            reject('createMenu出错了' + e);
        }
    });
};

// 删除菜单
function deleteMenu() {
    return new Promise(async (resolve, reject) => {
        try {
            // 获取access_token
            const data = await wechat.fetchAccessToken();
            // 定义请求地址
            const url = `https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=${data.access_token}`;
            // 发送请求
            const result = await rpn({method: 'GET', url, json: true});
            resolve(result);
        } catch (e) {
            reject('deleteMenu出错了' + e);
        }
    });
}

(async () => {
    let result = await deleteMenu();
    console.log(result);

    result = await createMenu(menuData)
    console.log(result);
})()


module.exports = {
    createMenu,
    deleteMenu
}